package offer;

/**
 * @Auther ZhanBo
 * @Date 2020/5/19
 */
public class Solution52 {

    public static void main(String[] args) {
        int[] arr1 = {4,1};
        int[] arr2 = {5,0,1};
        int[] arr3 = {8,4,5};
        ListNode headA = new ListNode(arr1);
        ListNode headB = new ListNode(arr2);
        ListNode common = new ListNode(arr3);
        mergeListNode(headA,common);
        mergeListNode(headB,common);

        System.out.println(getIntersectionNode(headA, headB));
    }

    /**
     * 合并链表
     * @param node
     * @param common
     */
    public static void mergeListNode(ListNode node , ListNode common){
        if(node==null||node.next==null)
            node.next =common;
        while (node.next!=null){
            node=node.next;
        }
        node.next =common;
    }

    /**
     * 输入两个链表，找出它们的第一个公共节点。
     * @param headA
     * @param headB
     * @return
     */
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode h1 = headA, h2 = headB;
        while (h1 != h2) {

            h1 = h1 == null ? headB : h1.next;
            h2 = h2 == null ? headA : h2.next;
        }

        return h1;

    }
}
